<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\CourseArrangeModel;
use App\Models\TeacherModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TeacherController extends Controller
{
    public function list(Request $request) {
        $teachers = TeacherModel::where('company_id', $request->company_id)->get();
        return self::sendOk($teachers);
    }
    public function page(Request $request) {
        $teachers = TeacherModel::where('company_id', $request->company_id)->paginate(10);
        return self::sendOk($teachers);
    }

    public function info(Request $request) {
        $teacher = TeacherModel::find($request->id);
        return self::sendOk($teacher);
    }

    public function add(Request $request) {
        $teacher = new TeacherModel();
        $teacher->fill($request->all());
        $teacher->save();
        return self::sendOk($teacher);
    }

    public function edit(Request $request) {
        $teacher = TeacherModel::find($request->id);
        $teacher->fill($request->all());
        $teacher->save();
        return self::sendOk($teacher);
    }
    public function delete(Request $request) {
        $teacher = TeacherModel::find($request->id);
        $teacher->delete();
        return self::sendOk();
    }

    public function count_course(Request $request) {
        $beginDate = $request->beginDate;
        $endDate = $request->endDate;
        $teachers = DB::table('teacher as t')
            ->leftJoin('course_arrange as ca', 't.id', '=', 'ca.teacher_id')
            ->select('ca.teacher_id',
                DB::raw('count(*) as arrange_count'), 
                DB::raw('sum(total_course_num) as course_count'),
                DB::raw('sum(total_course_money) as course_money'),
                DB::raw('sum(ca.commission) as commission'),
                't.name as teacher_name')
            ->groupBy('ca.teacher_id')
            ->where('t.company_id', $request->company_id)
            ->where('ca.status', 1)
            ->whereBetween('ca.date', [$beginDate, $endDate])
            ->orderBy('course_count', 'desc')
            ->get();
        return self::sendOk($teachers);
    }

    public function course_list(Request $request) {
        $beginDate = $request->beginDate;
        $endDate = $request->endDate;
        $courses = CourseArrangeModel::with('course', 'class')
        ->where('teacher_id', $request->teacherId)
        ->where('status', 1)
        ->whereBetween('date', [$beginDate, $endDate])
        ->orderBy('date', 'asc')
        ->get();
        return self::sendOk($courses);
    }
}
